﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;

namespace WindowsForm_Halcon_OCR
{
    public partial class Form1 : Form
    {//全局字段 HObject 表示图表类的数据
        HObject ho_Image, ho_GrayImage, ho_Region;
        HObject ho_ConnectedRegions, ho_SelectedwordRegions, ho_SortedRegions;
        HTuple hv_OCRHandle = new HTuple(), hv_Class = new HTuple();
        HTuple hv_Confidence = new HTuple(), hv_WindowHandle = new HTuple();
        HTuple hv_I = new HTuple();

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Clear();
        }

        public Form1()
        {
            InitializeComponent();
            HOperatorSet.GenEmptyObj(out ho_Image);
            HOperatorSet.GenEmptyObj(out ho_GrayImage);
            HOperatorSet.GenEmptyObj(out ho_Region);
            HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);
            HOperatorSet.GenEmptyObj(out ho_SelectedwordRegions);
            HOperatorSet.GenEmptyObj(out ho_SortedRegions);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "图片文件|*.jpg;*.png;*.bmp";  
            openFileDialog.Title = "请选择图片";
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                String filePath = openFileDialog.FileName;
                //out 引用传递
                HOperatorSet.ReadImage(out ho_Image, filePath);
                //获得图片的大小
                HOperatorSet.GetImageSize(ho_Image, out HTuple hv_Width, out HTuple hv_Height);
                //设置图像自适应
                DispImageAdapt(ho_Image, hwc1);    
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {   //灰度图转化
            HOperatorSet.Rgb1ToGray(ho_Image, out ho_GrayImage);
            //hwc1.HalconWindow.DispObj(ho_GrayImage);
            //设置颜色
            HOperatorSet.SetColor(hwc1.HalconWindow, "green");
            //阈值分割
            HOperatorSet.Threshold(ho_GrayImage, out ho_Region, 125, 255);
           // hwc1.HalconWindow.DispObj(ho_Region);
            HOperatorSet.Connection(ho_Region, out ho_ConnectedRegions);
            HOperatorSet.SetColored(hwc1.HalconWindow, 12);
            HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedwordRegions, "area", 
                "and", 700, 2500);
            HOperatorSet.SortRegion(ho_SelectedwordRegions, out ho_SortedRegions, "upper_left",
                "true", "column");
            HOperatorSet.CountObj(ho_SortedRegions, out HTuple hv_Count);
           //读取OMC文件分类器
           string pathMlp = Path.Combine(Directory.GetCurrentDirectory(), "yszx.omc");
           HOperatorSet.ReadOcrClassMlp(pathMlp, out hv_OCRHandle);
            //OCR识别
            HOperatorSet.DoOcrMultiClassMlp(ho_SortedRegions, ho_GrayImage, hv_OCRHandle,
         out hv_Class, out hv_Confidence);
            //显示 识别字符显示在Label中
            string[] result = hv_Class;
            foreach(string s in result)
            {
                label1.Text += s;
            }
            for ( int i = 1; i<= 4; i++)
            {
                
                using (HDevDisposeHelper dh = new HDevDisposeHelper())
                {
                   // disp_message(hwc1.HalconWindow, hv_Class.TupleSelect(i - 1), "image", 90,
                        //(60 * i) - 15, "red", "false");
                      HalconHelp.disp_message(hwc1.HalconWindow, hv_Class.TupleSelect(i - 1), "image", 90,
                        (60 * i) - 15, "red", "false");
                }

            }
            ho_Region.Dispose();
            ho_ConnectedRegions.Dispose();
            ho_SelectedwordRegions.Dispose();
            ho_SortedRegions.Dispose();
            hv_OCRHandle.Dispose();
            Clear();

        }



        private void DispImageAdapt(HObject image, HWindowControl hWindowControl)
        {
            try
            {
                // 获取图像尺寸
                HTuple hv_Width = new HTuple();
                HTuple hv_Height = new HTuple();
                HOperatorSet.GetImageSize(image, out hv_Width, out hv_Height);
                int imageWidth = hv_Width.I;
                int imageHeight = hv_Height.I;

                // 获取控件当前实际显示区域的尺寸（并非设计时尺寸）
                int controlWidth = hWindowControl.Width;
                int controlHeight = hWindowControl.Height;

                // 计算图像和控件的宽高比
                double imageRatio = (double)imageWidth / imageHeight;
                double controlRatio = (double)controlWidth / controlHeight;

                double partHeight, partWidth;
                int row1, column1, row2, column2;

                // 计算自适应的显示区域 (SetPart)
                if (controlRatio > imageRatio)
                {
                    // 控件更宽，高度方向填满，宽度方向上下留黑边
                    partHeight = imageHeight;
                    partWidth = partHeight * controlRatio;
                    row1 = (int)(-(partHeight - imageHeight) / 2.0); // 负坐标，从图像外开始画以实现居中
                    column1 = (int)(-(partWidth - imageWidth) / 2.0);
                    row2 = (int)(row1 + partHeight);
                    column2 = (int)(column1 + partWidth);
                }
                else
                {
                    // 控件更高，宽度方向填满，高度方向左右留黑边
                    partWidth = imageWidth;
                    partHeight = partWidth / controlRatio;
                    row1 = (int)(-(partHeight - imageHeight) / 2.0);
                    column1 = (int)(-(partWidth - imageWidth) / 2.0);
                    row2 = (int)(row1 + partHeight);
                    column2 = (int)(column1 + partWidth);
                }

                // 使用计算出的区域设置显示部分（居中显示，可能带黑边）
                HOperatorSet.SetPart(hWindowControl.HalconWindow, row1, column1, row2, column2);
                // 清除窗口并显示图像
                HOperatorSet.ClearWindow(hWindowControl.HalconWindow);
                HOperatorSet.DispObj(image, hWindowControl.HalconWindow);
            }
            catch (HalconException hex)
            {
                MessageBox.Show("Halcon Error: " + hex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }

        }
   private void  Clear()
            {
            ho_Image.Dispose();
            ho_GrayImage.Dispose();
            
            }
    
    }
}
